package main

import (
	"gitee.com/fu-ce-wei/pi-mapper/internal/config"
	"gitee.com/fu-ce-wei/pi-mapper/internal/handler"
	"gitee.com/fu-ce-wei/pi-mapper/pkg/logger"
	"github.com/gin-gonic/gin"
	"os"
	"path/filepath"
	"strings"
)

// setupRoutes 设置路由
func setupRoutes(router *gin.Engine, services *Services, logger *logger.Logger, cfg *config.Config) {
	// 创建处理器
	videoHandler := handler.NewVideoHandler(services.VideoService, logger)
	imageHandler := handler.NewImageHandler(services.ImageService, logger)
	resourceHandler := handler.NewResourceHandler(cfg, logger)

	// 静态文件服务
	setupStaticFileRoutes(router, cfg)

	// API路由组
	setupAPIRoutes(router, videoHandler, imageHandler, resourceHandler)

	// 资源文件服务路由
	setupResourceRoutes(router, resourceHandler)

	// 根路径和健康检查
	setupBasicRoutes(router, videoHandler)

	// 404处理
	setupNotFoundHandler(router)
}

// setupStaticFileRoutes 设置静态文件路由
func setupStaticFileRoutes(router *gin.Engine, cfg *config.Config) {
	// 设置统一的视频静态文件路由，支持多个根路径
	router.GET("/videos/*filepath", func(c *gin.Context) {
		// 获取请求的文件路径（如 "VideoDownUP1/77627a5a57696834.mp4"）
		requestedPath := c.Param("filepath")
		if requestedPath == "" || requestedPath == "/" {
			c.JSON(404, gin.H{"error": "文件路径不能为空"})
			return
		}

		// 去掉开头的斜杠
		requestedPath = strings.TrimPrefix(requestedPath, "/")

		// 解析路径前缀（如 "VideoDownUP1"）
		parts := strings.SplitN(requestedPath, "/", 2)
		if len(parts) < 2 {
			c.JSON(404, gin.H{"error": "文件路径格式错误"})
			return
		}

		pathPrefix := parts[0]
		relativePath := parts[1]

		// 根据路径前缀找到对应的根路径
		var rootPath string
		found := false
		for _, rp := range cfg.Scanner.RootPaths {
			if filepath.Base(rp) == pathPrefix {
				rootPath = rp
				found = true
				break
			}
		}

		if !found {
			c.JSON(404, gin.H{"error": "未找到对应的路径前缀: " + pathPrefix})
			return
		}

		// 构建完整的文件路径
		fullPath := filepath.Join(rootPath, relativePath)

		// 检查文件是否存在
		if _, err := os.Stat(fullPath); os.IsNotExist(err) {
			c.JSON(404, gin.H{"error": "文件不存在: " + requestedPath})
			return
		}

		// 提供文件
		c.File(fullPath)
	})

	// 图片静态文件路由（保持不变）
	router.Static("/images", cfg.Image.RootPath)
}

// setupAPIRoutes 设置API路由
func setupAPIRoutes(router *gin.Engine, videoHandler *handler.VideoHandler, imageHandler *handler.ImageHandler, resourceHandler *handler.ResourceHandler) {
	apiV1 := router.Group("/api/v1")
	{
		// 视频相关路由
		setupVideoRoutes(apiV1, videoHandler)

		// 图片相关路由
		setupImageRoutes(apiV1, imageHandler)

		// 系统相关路由
		apiV1.GET("/health", videoHandler.HealthCheck)

		// 资源相关路由
		setupResourceAPIRoutes(apiV1, resourceHandler)
	}
}

// setupVideoRoutes 设置视频路由
func setupVideoRoutes(apiGroup *gin.RouterGroup, videoHandler *handler.VideoHandler) {
	videos := apiGroup.Group("/videos")
	{
		videos.GET("/list", videoHandler.GetVideoList)
		videos.GET("/:filename", videoHandler.GetVideoInfo)
	}
}

// setupImageRoutes 设置图片路由
func setupImageRoutes(apiGroup *gin.RouterGroup, imageHandler *handler.ImageHandler) {
	images := apiGroup.Group("/images")
	{
		images.GET("/list", imageHandler.GetImageList)
		images.GET("/:filename", imageHandler.GetImageInfo)
	}
}

// setupResourceAPIRoutes 设置资源API路由
func setupResourceAPIRoutes(apiGroup *gin.RouterGroup, resourceHandler *handler.ResourceHandler) {
	resources := apiGroup.Group("/resources")
	{
		resources.GET("/sex", resourceHandler.GetSexResourceList)
	}
}

// setupResourceRoutes 设置资源文件服务路由
func setupResourceRoutes(router *gin.Engine, resourceHandler *handler.ResourceHandler) {
	router.GET("/resources/sex/:filename", resourceHandler.ServeSexResource)
}

// setupBasicRoutes 设置基础路由
func setupBasicRoutes(router *gin.Engine, videoHandler *handler.VideoHandler) {
	// 根路径
	router.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "PiMapper API Server",
			"version": version,
		})
	})

	// 健康检查
	router.GET("/health", videoHandler.HealthCheck)
}

// setupNotFoundHandler 设置404处理
func setupNotFoundHandler(router *gin.Engine) {
	router.NoRoute(func(c *gin.Context) {
		c.JSON(404, gin.H{
			"message": "接口不存在",
			"path":    c.Request.URL.Path,
		})
	})
}
